import { Form, Input, Modal } from "antd";
import { useForm } from "antd/es/form/Form";
import { savePage } from "../../interfaces";
import { GFS } from "@/hooks/useAssignGlobalProps";

interface AddPageModalProps {
  isOpen: boolean;
  handleClose: Function;
  freshPage: Function
}

const layout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 20 },
};

export interface SavePage {
  id?: number;
  label: string;
  path: string;
  icon: string;
  schema?: string
}

export function AddPageModal(props: AddPageModalProps) {
  const [form] = useForm<SavePage>();

  const handleOk = async function () {
    await form.validateFields();
    const values = form.getFieldsValue();

    try {
      const res = await savePage(values);

      if (res.status === 201 || res.status === 200) {
        GFS.message.success(res.data.message);
        setTimeout(() => {
          form.resetFields();
          props.handleClose();
          props.freshPage()
        }, 700);
      }
    } catch (e: any) {
      GFS.message.error(e.response?.data?.message || "系统繁忙，请稍后再试");
    }
  };

  return (
    <Modal
      title="新增页面"
      open={props.isOpen}
      onOk={handleOk}
      onCancel={() => props.handleClose()}
    >
      <Form form={form} colon={false} {...layout}>
        <Form.Item
          label="名称"
          name="label"
          rules={[{ required: true, message: "请输入名称!" }]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          label="路径"
          name="path"
          rules={[{ required: true, message: "请输入路径!" }]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          label="图标"
          name="icon"
        >
          <Input />
        </Form.Item>
      </Form>
    </Modal>
  );
}
